package com.okilo.online.app.tools.helper

import android.content.Context
import android.content.Intent
import androidx.core.net.toUri
import com.okilo.online.app.OkiloApplication
import com.okilo.online.app.common.OkiloComAct
import com.okilo.online.app.event.OkiloEventPointType
import com.okilo.online.app.request.HttpHelper
import com.okilo.online.app.lib.analyse.util.OkiloReviewUtil
import com.okilo.online.app.act.OkiloFeedbackAct
import com.okilo.online.app.dialog.OkiloRateScoreDlog
import com.okilo.online.app.tools.log.OkiloLog
import com.okilo.online.app.tools.shared.OkiloSharedHp
import com.okilo.online.app.tools.shared.OkiloSharedKey
import org.json.JSONObject

/**
 * OkiloLoan
 * @Author wwdeng
 * @CreateTime: 2024/11/13 16:26
 * @Annotation：评分帮助类
 */
object OkiloScoreDialogHp {

    /**
     * 展示评分
     */
    fun showStarDialog(context: Context, data: JSONObject){

        // 优先处理活跃窗口弹窗
        if (tryShowActiveDialog(context, data)) {
            return
        }
        // 如果活跃窗口未显示，则处理普通窗口弹窗
        tryShowNormalDialog(context, data)
    }

    private fun tryShowActiveDialog(context: Context, data: JSONObject): Boolean {
        val activeWindowObj = data.optJSONObject("activeWindow") ?: return false

        // 检查开关状态
        if (activeWindowObj.optString("switch") != "YES") {
            return false
        }

        // 检查是否需要计数限制
        if (data.optBoolean("isNeedAdd",false)) {
            val totalNum = activeWindowObj.optInt("num")
            val currentNum = OkiloSharedHp.gOkiloSharedInt(OkiloSharedKey.SP_OKILO_DIALOG_ACTIVE_NUM)

            if (currentNum >= totalNum) {
                return false
            }

            // 更新计数
            OkiloSharedHp.sOkiloSharedData(OkiloSharedKey.SP_OKILO_DIALOG_ACTIVE_NUM, currentNum + 1)
        }

        // 显示弹窗
        val content = activeWindowObj.optString("content")
        showActiveStarDialog(context, content)
        return true
    }

    private fun tryShowNormalDialog(context: Context, data: JSONObject) {
        val normalWindowObj = data.optJSONObject("normalWindow") ?: return

        // 检查开关状态
        if (normalWindowObj.optString("switch") != "YES") {
            return
        }

        if (data.optBoolean("isNeedAdd",false)) {
            val totalNum = normalWindowObj.optInt("num")
            val currentNum = OkiloSharedHp.gOkiloSharedInt(OkiloSharedKey.SP_OKILO_DIALOG_NORMAL_NUM)

            if (currentNum >= totalNum) {
                return
            }

            // 更新计数
            OkiloSharedHp.sOkiloSharedData(OkiloSharedKey.SP_OKILO_DIALOG_NORMAL_NUM, currentNum + 1)
        }

        // 显示弹窗
        val content = normalWindowObj.optString("content")
        showNormalStarDialog(context, content)
    }

    /**
     * activeWindow
     */
    private fun showActiveStarDialog(context: Context, tips: String?){
        showNormalStarDialog(context,tips)
    }

    /**
     * normalWindow
     */
    private fun showNormalStarDialog(context: Context, tips: String?){
        val normalDialog = OkiloRateScoreDlog(context, createStarDialogCallback(context))
        normalDialog.setCancelable(true)
        normalDialog.setCanceledOnTouchOutside(false)
        normalDialog.show()
        normalDialog.sOkiloRateScoreTipsText(tips)
    }

    /**
     * 创建评分回调
     */
    private fun createStarDialogCallback(context: Context): IStarDialogCallback {
        return object : IStarDialogCallback {
            override fun completeScoringCount(count: Int) {
                handleScoringResult(context, count)
            }
        }
    }

    /**
     * 处理评分结果
     */
    private fun handleScoringResult(context: Context, count: Int) {
        OkiloLog.i(">>>>>>>>>>score num：$count")
        // 上报评分事件
        HttpHelper.addPoint(OkiloEventPointType.OKILO_CLICK_TRACK.SCORE_RATE, count.toString())
        /**
         * 数量 >= 4  ->  跳转Google 评分 （AppReviewUtil.launchReviewFlow() ）
         * 数量 < 4   ->  跳转意见反馈  ( UserFeedbackAct )
         */
        if (count < 4) {
            // 跳转意见反馈
            OkiloFeedbackAct.start(context, count.toString())
        } else {
            // 跳转Google评分
            launchAppReview(context)
        }
    }

    /**
     * 启动应用评分
     */
    private fun launchAppReview(context: Context) {
        val activity = context as? OkiloComAct ?: return
        OkiloReviewUtil.launchReviewFlow(activity, completed = { success ->
            OkiloLog.i(">>>>>completed>>>>>>>>>>$success")
            if (!success) {
                // 评分流程失败，跳转到应用市场
                enterMarket()
            }
        })
    }


    /**
     * 跳转到应用商店
     */
    private fun enterMarket(){
        try {
            val intent = Intent(Intent.ACTION_VIEW).apply {
                data = "https://play.google.com/store/apps/details?id=${OkiloApplication.app.packageName}".toUri()
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }
            OkiloApplication.app.startActivity(intent)
        } catch (e: Exception) {
            OkiloLog.e("Failed to open market: ${e.message}")
        }
    }

    interface IStarDialogCallback {
        //返回评星数量
        fun completeScoringCount(count: Int)
    }
}